<template>
  <view class="login-container">
    <!-- 顶部背景和图标 -->
    <view class="login-bg">
      <!-- 白色矩形装饰 -->
      <view class="rect1 bg-rect" />
      <view class="bg-rect rect2" />
      <view class="bg-rect rect3" />
      <view class="bg-rect rect4" />
      <view class="bg-rect rect5" />
    </view>

    <view class="login-top">
      <view class="logo-wrap">
        <image src="https://ceshiweb.picaime.com/static/images/login/login_top.png" class="login-logo" />
      </view>
      <view class="title">
        Hello!<br>欢迎登录云批宝
      </view>
    </view>

    <!-- 登录表单 - 验证码登录 -->
    <view v-if="loginType === 'code'" class="login-form">
      <view class="input-item-wrap">
        <text class="prefix">
          +86
        </text>
        <input v-model="phone" class="input-item" type="number" placeholder="请输入手机号">
      </view>

      <view class="input-group">
        <view class="input-wrap">
          <input v-model="code" class="input-code" type="number" placeholder="请输入验证码">
          <view class="get-code-btn" @tap="getVerifyCode">
            获取验证码
          </view>
        </view>
        <view v-if="showError" class="error-tip">
          <up-icon name="error-circle" color="#e54d42" size="12" />
          <text>验证码错误，请重新输入</text>
        </view>
      </view>

      <button class="login-btn" @tap="submit">
        立即登录
      </button>

      <view class="login-option">
        <text class="login-switch" @tap="switchLoginType">
          账号密码登录
        </text>
      </view>
    </view>

    <!-- 登录表单 - 密码登录 -->
    <view v-else class="login-form">
      <view class="input-item-wrap">
        <input v-model="phone" class="input-item" type="number" placeholder="请输入手机号">
      </view>

      <view class="input-group">
        <input v-model="password" class="input-code" type="text" password placeholder="请输入密码">
        <view v-if="showError" class="error-tip">
          <up-icon name="error-circle" color="#e54d42" size="12" />
          <text>密码错误，请重新输入</text>
        </view>
      </view>

      <button class="login-btn" @tap="submit">
        立即登录
      </button>

      <view class="login-option">
        <text class="login-switch" @tap="switchLoginType">
          验证码登录
        </text>
      </view>
    </view>

    <!-- 社交登录 -->
    <view class="login-social">
      <view class="social-item">
        <view class="wechat-icon">
          <button open-type="getPhoneNumber" class="loginBtn" @getphonenumber="getPhoneNumber">
            <up-icon name="weixin-fill" color="#07c160" size="40" />
          </button>
        </view>
      </view>
    </view>

    <!-- 协议 -->
    <view class="login-agreement">
      <view class="agreement-text">
        <view class="checkbox-wrap">
          <up-checkbox v-model="agreement" shape="circle" active-color="#07c160" />
        </view>
        已阅读并同意
        <text class="link" @tap="goToAgreement">
          《用户协议》
        </text>
        和
        <text class="link" @tap="goToPrivacy">
          《隐私政策》
        </text>
      </view>
    </view>

    <!-- 多账户选择弹窗 -->
    <AccountSelector
      :show="showAccountSelector" :accounts="accountOptions" @confirm="handleAccountConfirm"
      @cancel="handleAccountCancel"
    />
  </view>
</template>

<script setup lang="ts">
import type {
  AccountOption,
  LoginByCodeRes,
  LoginRes,
} from '@/api/user/types';
import AccountSelector from '@/components/AccountSelector/index.vue';
import {
  HOME_PATH,
  isTabBarPath,
  LOGIN_PATH,
  removeQueryString,
} from '@/router';
import { useUserStore } from '@/store';
import AccountCacheManager from '@/utils/accountCache';

const userStore = useUserStore();
const phone = ref<string>('');
const code = ref<string>('');
const password = ref<string>('');
const showError = ref<boolean>(false);
const agreement = ref<boolean>(true);
const loginType = ref<'code' | 'password'>('password'); // 默认密码登录
const showAccountSelector = ref<boolean>(false); // 多账户选择弹窗
const accountOptions = ref<AccountOption[]>([]); // 账户选项列表
const wechatPhone = ref<string>(''); // 微信登录获取的手机号
let redirect = HOME_PATH;

// 切换登录类型
function switchLoginType() {
  loginType.value = loginType.value === 'code' ? 'password' : 'code';
  showError.value = false;
  code.value = '';
  password.value = '';
}

// 获取验证码
function getVerifyCode() {
  if (!phone.value) {
    uni.$u.toast('请输入手机号');
    return;
  }

  uni.showLoading({
    title: '发送中...',
  });

  setTimeout(() => {
    uni.hideLoading();
    uni.$u.toast('验证码已发送');
  }, 1000);
}

async function submit() {
  // 验证手机号
  if (!phone.value) {
    uni.$u.toast('请输入手机号');
    return;
  }

  // 验证协议是否勾选
  if (!agreement.value) {
    uni.$u.toast('请阅读并同意协议');
    return;
  }

  // 登录页面不检查缓存，直接进行登录请求

  if (loginType.value === 'code') {
    // 验证码登录
    if (!code.value) {
      uni.$u.toast('请输入验证码');
      return;
    }

    try {
      uni.showLoading({
        title: '登录中...',
      });

      // 登录请求
      const res = (await userStore.login({
        account: phone.value,
        password: code.value,
      })) as LoginRes;

      handleLoginResponse(res);
    }
    catch {
      handleLoginError();
    }
  }
  else {
    // 密码登录
    if (!password.value) {
      uni.$u.toast('请输入密码');
      return;
    }

    try {
      uni.showLoading({
        title: '登录中...',
      });

      // 登录请求
      const res = (await userStore.login({
        account: phone.value,
        password: password.value,
      })) as LoginRes;

      handleLoginResponse(res);
    }
    catch {
      handleLoginError();
    }
  }
}

// 处理登录响应
function handleLoginResponse(res: LoginRes) {
  uni.hideLoading();
  if (res.code === 200) {
    // 检查是否为多账户响应
    if (res.data?.info && Array.isArray(res.data.info)) {
      // 多账户情况，直接替换缓存并显示选择弹窗
      accountOptions.value = res.data.info;
      showAccountSelector.value = true;
      AccountCacheManager.saveAccounts(
        phone.value,
        res.data.info,
        password.value,
      );
      return;
    }

    // 单账户情况，直接处理登录
    if (res.data?.token) {
      handleSingleAccountLogin(res.data.token);
    }
    else {
      // 如果没有token，说明登录有问题
      showError.value = true;
      uni.showToast({
        title: '登录信息不完整',
        icon: 'none',
      });
    }
  }
  else {
    showError.value = true;
    uni.showToast({
      title: res.msg || '登录失败',
      icon: 'none',
    });
  }
}

// 处理单账户登录成功
function handleSingleAccountLogin(_token: string) {
  // 注意：token已经在 userStore.login 方法中设置
  // 用户信息也已经在 userStore.login 方法中通过 getUserInfoByToken 接口获取并设置
  // 这里不再需要手动设置token和用户信息

  uni.showToast({
    title: '登录成功',
    icon: 'success',
  });

  setTimeout(() => {
    uni.$u.route({
      type: isTabBarPath(redirect) ? 'switchTab' : 'redirectTo',
      url: redirect,
    });
  }, 800);
}

// 处理账户选择确认
async function handleAccountConfirm(selectedAccount: AccountOption) {
  showAccountSelector.value = false;

  try {
    uni.showLoading({
      title: '登录中...',
    });

    // 判断是否为微信登录的多商户选择
    if (wechatPhone.value) {
      // 微信多商户登录，调用专门的接口
      const res = await userStore.wxMultiMerchantLogin(wechatPhone.value, selectedAccount.id);
      handleWechatMultiMerchantLoginResponse(res);
    }
    else {
      // 普通登录的多账户选择
      const res = (await userStore.login({
        account: selectedAccount.mobile,
        password: loginType.value === 'code' ? code.value : password.value,
        id: selectedAccount.id, // 添加账户ID参数
      })) as LoginRes;

      handleLoginResponse(res);
    }
  }
  catch {
    handleLoginError();
  }
}

// 处理账户选择取消
function handleAccountCancel() {
  showAccountSelector.value = false;
  // 清除微信登录状态
  wechatPhone.value = '';
}

// 处理微信多商户登录响应
function handleWechatMultiMerchantLoginResponse(res: any) {
  uni.hideLoading();
  if (res.code === 200) {
    console.log('微信多商户登录成功:', res);

    uni.showToast({
      title: '登录成功',
      icon: 'success',
    });

    setTimeout(() => {
      uni.$u.route({
        type: isTabBarPath(redirect) ? 'switchTab' : 'redirectTo',
        url: redirect,
      });
    }, 800);
  }
  else {
    uni.showToast({
      title: res.msg || '登录失败',
      icon: 'none',
    });
  }
  // 清除微信登录状态
  wechatPhone.value = '';
}

// 处理登录错误
function handleLoginError() {
  uni.hideLoading();
  showError.value = true;
  uni.showToast({
    title: '登录失败',
    icon: 'none',
  });
}

// 获取微信手机号
async function getPhoneNumber(e: any) {
  // 验证协议是否勾选
  if (!agreement.value) {
    uni.$u.toast('请阅读并同意协议');
    return;
  }
  console.log(e.detail);

  // 检查是否获取到手机号授权
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    try {
      uni.showLoading({
        title: '微信登录中...',
      });

      // 调用微信小程序授权登录
      const res = await userStore.authLogin(e.detail.code);
      handleWechatLoginResponse(res as LoginByCodeRes);
    }
    catch (_error) {
      console.error('微信登录失败:', _error);
      handleLoginError();
    }
  }
  else {
    uni.showToast({
      title: '需要手机号授权才能登录',
      icon: 'none',
    });
  }
}

// 处理微信登录响应
function handleWechatLoginResponse(res: LoginByCodeRes) {
  uni.hideLoading();
  if (res.code === 200) {
    console.log('微信登录响应:', res);

    // 检查是否为多账户响应（直接返回数组）
    if (Array.isArray(res.data)) {
      console.log('微信登录返回多账户数组格式');
      accountOptions.value = res.data.map((item: any) => ({
        id: item.id,
        name: item.name,
        mobile: item.mobile,
        dangkou_name: item.admin?.real_name || item.name,
      }));
      wechatPhone.value = res.data[0]?.mobile || '';
      showAccountSelector.value = true;
      return;
    }

    // 检查是否为多账户响应（data包含info数组）
    if (res.data && Array.isArray(res.data.info)) {
      console.log('微信登录返回多账户info格式');
      accountOptions.value = res.data.info.map((item: any) => ({
        id: item.id,
        name: item.name,
        mobile: item.mobile,
        dangkou_name: item.admin?.real_name || item.name,
      }));
      wechatPhone.value = res.data.info[0]?.mobile || '';
      showAccountSelector.value = true;
      return;
    }

    // 单账户情况，直接登录成功
    console.log('微信登录成功:', res);
    uni.showToast({
      title: '微信登录成功',
      icon: 'success',
    });

    setTimeout(() => {
      uni.$u.route({
        type: isTabBarPath(redirect) ? 'switchTab' : 'redirectTo',
        url: redirect,
      });
    }, 800);
  }
  else {
    uni.showToast({
      title: res.msg || '微信登录失败',
      icon: 'none',
    });
  }
}

// 跳转到用户协议
function goToAgreement() {
  uni.navigateTo({
    url: '/pages/common/agreement/index',
  });
}

// 跳转到隐私政策
function goToPrivacy() {
  uni.navigateTo({
    url: '/pages/common/privacy/index',
  });
}

onLoad((options: any) => {
  if (options.redirect && removeQueryString(options.redirect) !== LOGIN_PATH) {
    redirect = decodeURIComponent(options.redirect);
  }
});
</script>

<style lang="scss" scoped>
.loginBtn {
  background-color: transparent;
  border: none;
  padding: 0;
  margin: 0;
  width: 100rpx;
  height: 100rpx;
  display: flex;

  &::after {
    border: none;
  }
}

.login-container {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  min-height: 96vh;
  background-color: #ffffff;
  position: relative;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  background: linear-gradient(to bottom, #b8f0c2, #edfbef);
  z-index: -1;
  border-bottom-left-radius: 30rpx;
  border-bottom-right-radius: 30rpx;
  overflow: hidden;

  .bg-rect {
    position: absolute;
    background-color: rgba(255, 255, 255, 0.5);
    border-radius: 12rpx;
    transform: rotate(-15deg);
  }

  .rect1 {
    width: 120rpx;
    height: 60rpx;
    top: 50rpx;
    right: 80rpx;
  }

  .rect2 {
    width: 80rpx;
    height: 100rpx;
    top: 150rpx;
    right: 40rpx;
  }

  .rect3 {
    width: 140rpx;
    height: 70rpx;
    top: 40rpx;
    left: 60rpx;
  }

  .rect4 {
    width: 90rpx;
    height: 120rpx;
    top: 180rpx;
    left: 30rpx;
  }

  .rect5 {
    width: 110rpx;
    height: 80rpx;
    top: 120rpx;
    left: 180rpx;
  }
}

.login-top {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
  margin-top: 60rpx;
  position: relative;

  .logo-wrap {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background-color: #07c160;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  }

  .login-logo {
    width: 60rpx;
    height: 60rpx;
  }

  .title {
    font-size: 36rpx;
    font-weight: 600;
    text-align: center;
    color: #333;
    line-height: 1.5;
  }
}

.login-form {
  margin: 0 30rpx;

  .input-item-wrap {
    display: flex;
    align-items: center;
    height: 100rpx;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 20rpx;

    .prefix {
      font-size: 30rpx;
      color: #333;
      margin-right: 10rpx;
      min-width: 60rpx;
    }

    .input-item {
      flex: 1;
      height: 100%;
      font-size: 30rpx;
      color: #333;
    }
  }

  .input-group {
    position: relative;
    margin-bottom: 60rpx;

    .input-wrap {
      display: flex;
      align-items: center;
      height: 100rpx;
      border-bottom: 1px solid #f2f2f2;
    }

    .input-code {
      flex: 1;
      height: 100%;
      font-size: 30rpx;
      color: #333;
    }

    .get-code-btn {
      padding: 10rpx 20rpx;
      font-size: 26rpx;
      color: #07c160;
      border-left: 1px solid #f2f2f2;
    }

    .error-tip {
      position: absolute;
      bottom: -40rpx;
      left: 0;
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #e54d42;

      text {
        margin-left: 5rpx;
      }
    }
  }

  .login-btn {
    margin-top: 80rpx;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    color: #fff;
    text-align: center;
    background-color: #07c160;
    border-radius: 45rpx;
    border: none;
    box-shadow: 0 4rpx 10rpx rgba(7, 193, 96, 0.3);
    transition: all 0.3s;

    &:active {
      transform: scale(0.98);
      box-shadow: 0 2rpx 6rpx rgba(7, 193, 96, 0.3);
    }
  }

  .login-option {
    margin-top: 40rpx;
    text-align: center;

    .login-switch {
      font-size: 28rpx;
      color: #666;
      text-decoration: underline;
    }
  }
}

.login-social {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;

  .social-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .wechat-icon {
      width: 80rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f8f8f8;
      border-radius: 50%;
      box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
    }
  }
}

.login-agreement {
  margin-top: 40rpx;
  padding: 20rpx 0;
  text-align: center;

  .agreement-text {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
    color: #999;

    .checkbox-wrap {
      display: flex;
      align-items: center;
      margin-right: 10rpx;
    }

    .link {
      color: #07c160;
    }
  }
}
</style>
